package com.demo.redis.subpub;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.Topic;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

@Component
@ConditionalOnProperty(value = "testPubSub",havingValue = "true")
public class PubSubMain implements InitializingBean {

    @Autowired
    Publisher publisher;

    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer;
    @Override
    public void afterPropertiesSet() throws Exception {
        /*new Thread(){
            @Override
            public void run() {
                while (true){
                    publisher.pub("chat","hello chat");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();*/

        System.out.println("==========================");
        new Thread(){
            @Override
            public void run() {
                while (true){
                    MessageBean message = new MessageBean("hello chat");
                    //byte[] bytes = genericJackson2JsonRedisSerializer.serialize(message);
                    JdkSerializationRedisSerializer serializer = new JdkSerializationRedisSerializer();
                    byte[] bytes = serializer.serialize(message);
                    publisher.pub("chatMessage",bytes);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();

    }




}
